/*
 * Copyright (C) 2004-2013 L2J DataPack
 *
 * This file is part of L2J DataPack.
 *
 * L2J DataPack is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * L2J DataPack is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package custom.Services;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.logging.Logger;

import com.l2device.gameserver.Config;
import com.l2device.gameserver.L2DatabaseFactory;
import com.l2device.gameserver.datatables.CharNameTable;
import com.l2device.gameserver.datatables.ClanTable;
import com.l2device.gameserver.model.actor.L2Npc;
import com.l2device.gameserver.model.actor.instance.L2PcInstance;
import com.l2device.gameserver.model.olympiad.OlympiadManager;
import com.l2device.gameserver.model.quest.Quest;
import com.l2device.gameserver.model.quest.QuestState;
import com.l2device.gameserver.network.serverpackets.MagicSkillUse;
 
/**
 * @author Colet
 * Interlude rework SweeTs
 * Reworked Disco
 */
public class Services extends Quest
{
    public static final Logger _log = Logger.getLogger(Services.class.getName());
   
    // NPC Id
    int servicesNpc = 50008;
   
    // Noble Items
    int nobleItemId = Config.SERVICE_NOBLE_ITEM_ID;
    int nobleItemCount = Config.SERVICE_NOBLE_ITEM_COUNT;
   
    // PK Reduce Items
    int pkReduceItemId = Config.SERVICE_PK_ITEM_ID;
    int pkReduceItemCount = Config.SERVICE_PK_ITEM_COUNT;
   
    // Change Name Items
    int changeNameItemId = Config.SERVICE_NAME_ITEM_ID;
    int changeNameItemCount = Config.SERVICE_NAME_ITEM_COUNT;
    boolean logNameChanges = true;
   
    // Change Clan Name Items
    int changeClanNameItemId = Config.SERVICE_CLAN_NAME_ITEM_ID;
    long changeClanNameItemCount = Config.SERVICE_CLAN_NAME_ITEM_COUNT;
    boolean logClanNameChanges = true;
    int clanMinLevel = 5;
    
    // Clan Level Items
    int[] clanLevelItemsId =
    {
    	Config.SERVICE_CLAN_LVL5TO6_ITEM_ID, // Level 5 to 6
    	Config.SERVICE_CLAN_LVL6TO7_ITEM_ID, // Level 6 to 7
    	Config.SERVICE_CLAN_LVL7TO8_ITEM_ID, // Level 7 to 8
    };
    
    int[] clanLevelItemsCount =
    {
    		Config.SERVICE_CLAN_LVL5TO6_ITEM_COUNT, // Level 5 to 6
    		Config.SERVICE_CLAN_LVL6TO7_ITEM_COUNT, // Level 6 to 7
    		Config.SERVICE_CLAN_LVL7TO8_ITEM_COUNT, // Level 7 to 8
    };
    
    // Clan Reputation Points Items
    int clanReputationPointsItemId = Config.SERVICE_CLAN_REP_ITEM_ID;
    int clanReputationPointsItemCount = Config.SERVICE_CLAN_REP_ITEM_COUNT;
    
    // Change Gender Items
    int changeGenderItemId = Config.SERVICE_SEX_CHANGE_ITEM_ID;
    int changeGenderItemCount = Config.SERVICE_SEX_CHANGE_ITEM_COUNT;
    
    public Services(int questId, String name, String descr)
    {
        super(questId, name, descr);
       
        addStartNpc(servicesNpc);
        addFirstTalkId(servicesNpc);
        addTalkId(servicesNpc);
    }
   
    public static void main(String[] args)
    {
        new Services(-1, Services.class.getSimpleName(), "custom");
    }
   
    @Override
    public String onFirstTalk(L2Npc npc, L2PcInstance player)
    {
        if (player.getQuestState(getName()) == null)
        {
            newQuestState(player);
        }
        else if (player.isInCombat())
        	return "Services-Blocked.htm";
        
        else if (player.getPvpFlag() == 1)
        	return "Services-Blocked.htm";
        
        else if (player.getKarma() != 0)
        	return "Services-Blocked.htm";
        
        else if (OlympiadManager.getInstance().isRegistered(player))
        	return "Services-Blocked.htm";
        
        else if (player.isDead() || player.isFakeDeath())
        	return "Services-Blocked.htm";
        
        return "Services.htm";
    }
   
    @Override
    public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
    {
        String htmlText = event;
        QuestState st = player.getQuestState(getName());
       
        if (event.equals("setNoble"))
        {
            if (!player.isNoble())
            {
                if (st.getQuestItemsCount(nobleItemId) >= nobleItemCount)
                {
                    st.takeItems(nobleItemId, nobleItemCount);
                    player.setNoble(true,true);
                    player.setTarget(player);
                    player.broadcastPacket(new MagicSkillUse(player, 5103, 1, 1000, 0));
                    player.broadcastUserInfo();
                    return "NoblesseServices-Success.htm";
                }
				return "NoblesseServices-NoItems.htm";
            }
			return "NoblesseServices-AlredyNoble.htm";
        }
        else if (event.equals("levelUpClan"))
        {
        	if (player.getClan() == null)
            {
            	return "ClanLevelUp-NoClan.htm";
            }
        	else if (!player.isClanLeader())
        	{
        		return "ClanLevelUp-NoLeader.htm";
        	}
        	else
        	{
        		if (player.getClan().getLevel() == 8)
        		{
        			return "ClanLevelUp-MaxLevel.htm";
        		}
				if (((player.getClan().getLevel() <= 1) || (player.getClan().getLevel() == 2) || (player.getClan().getLevel() == 3) || (player.getClan().getLevel() == 4)))
				{
					player.getClan().changeLevel(player.getClan().getLevel() + 1);
					player.getClan().broadcastClanStatus();
					player.sendMessage("У вашего клана теперь " + player.getClan().getLevel() + " уровень.");
				    player.setTarget(player);
				    player.broadcastPacket(new MagicSkillUse(player, 5103, 1, 1000, 0));
				    return "ClanLevelUp.htm";
				}
				else if (player.getClan().getLevel() == 5)
				{
					if (st.getQuestItemsCount(clanLevelItemsId[0]) >= clanLevelItemsCount[0])
					{
						st.takeItems(clanLevelItemsId[0], clanLevelItemsCount[0]);
						player.getClan().changeLevel(player.getClan().getLevel() + 1);
						player.getClan().broadcastClanStatus();
						player.sendMessage("У вашего клана теперь " + player.getClan().getLevel() + " уровень.");
				        player.setTarget(player);
				        player.broadcastPacket(new MagicSkillUse(player, 5103, 1, 1000, 0));
				        return "ClanLevelUp.htm";
					}
					return "ClanLevelUp-NoItems.htm";
				}
				else if (player.getClan().getLevel() == 6)
				{
					if (st.getQuestItemsCount(clanLevelItemsId[1]) >= clanLevelItemsCount[1])
					{
						st.takeItems(clanLevelItemsId[1], clanLevelItemsCount[1]);
						player.getClan().changeLevel(player.getClan().getLevel() + 1);
						player.getClan().broadcastClanStatus();
						player.sendMessage("У вашего клана теперь " + player.getClan().getLevel() + " уровень.");
				        player.setTarget(player);
				        player.broadcastPacket(new MagicSkillUse(player, 5103, 1, 1000, 0));
				        return "ClanLevelUp.htm";
					}
					return "ClanLevelUp-NoItems.htm";
				}
				else if (player.getClan().getLevel() == 7)
				{
					if (st.getQuestItemsCount(clanLevelItemsId[2]) >= clanLevelItemsCount[2])
					{
						st.takeItems(clanLevelItemsId[2], clanLevelItemsCount[2]);
						player.getClan().changeLevel(player.getClan().getLevel() + 1);
						player.getClan().broadcastClanStatus();
						player.sendMessage("У вашего клана теперь " + player.getClan().getLevel() + " уровень.");
				        player.setTarget(player);
				        player.broadcastPacket(new MagicSkillUse(player, 5103, 1, 1000, 0));
				        return "ClanLevelUp.htm";
					}
					return "ClanLevelUp-NoItems.htm";
				}
				
				try (Connection con = L2DatabaseFactory.getInstance().getConnection())
				{
					PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET clan_level=? WHERE clan_id=?");
					statement.setInt(1, player.getClan().getLevel());
					statement.setInt(2, player.getClan().getClanId());
					statement.execute();
					statement.close();
				}
				catch (Exception e)
				{
					_log.info("Error updating clan level for player " + player.getName() + ". Error: " + e);
				}
				
				player.getClan().broadcastClanStatus();
				return "ClanLevelUp.htm";
        	}
        }
        else if (event.equals("changeGender"))
        {
        	if (st.getQuestItemsCount(changeGenderItemId) >= changeGenderItemCount)
        	{
            	st.takeItems(changeGenderItemId, changeGenderItemCount);
            	player.getAppearance().setSex(player.getAppearance().getSex() ? false : true);
                player.setTarget(player);
                player.broadcastPacket(new MagicSkillUse(player, 5103, 1, 1000, 0));
            	player.broadcastUserInfo();
            	return "ChangeGender-Success.htm";
        	}
			return "ChangeGender-NoItems.htm";
        }
        else if (event.startsWith("changeName"))
        {
            try
            {
                String newName = event.substring(11);
               
                if (st.getQuestItemsCount(changeNameItemId) >= changeNameItemCount)
                {                                                      
                    if (newName == null)
                    {                                                      
                        return "ChangeName.htm";
                    }
					if (!newName.matches("^[a-zA-Z0-9]+$"))
					{
					    player.sendMessage("Некорректный ник.");
					    return "ChangeName.htm";
					}
					else if (newName.length() > 16 || newName.length() < 3)
					{
					    player.sendMessage("Ник должен состоять минимум из 3,максимум из 16 символов.");
					    return "ChangeName.htm";
					}
					else if (newName.equals(player.getName()))
					{
					    player.sendMessage("Некорректно введен ник, используйте другой ник.");
					    return "ChangeName.htm";
					}
					else if (CharNameTable.doesCharNameExist(newName))
					{
					    player.sendMessage("Ник " + newName + " занят, используйте другой ник.");
					    return "ChangeName.htm";
					}
					else
					{
					    st.takeItems(changeNameItemId, changeNameItemCount);
					    player.setName(newName);
					    player.store();
					    player.sendMessage("Вы сменили ник: " + newName);
					    player.broadcastUserInfo();
					    player.getClan().broadcastClanStatus();
					    return "ChangeName-Success.htm";
					}
                }
				return "ChangeName-NoItems.htm";
            }
            catch (Exception e)
            {
                return "ChangeName.htm";
            }
        }
        else if (event.startsWith("reducePks"))
        {
            try
            {
                String pkReduceString = event.substring(10);
                int pkReduceCount = Integer.parseInt(pkReduceString);
                
                if (player.getPkKills() != 0)
                {
                    if (pkReduceCount == 0)
                    {
                        player.sendMessage("У вас и так 0 PK.");
                        return "PkServices.htm";
                    }
					if (st.getQuestItemsCount(pkReduceItemId) >= pkReduceItemCount)
					{
					    st.takeItems(pkReduceItemId, pkReduceItemCount * pkReduceCount);
					    player.setPkKills(player.getPkKills() - pkReduceCount);
					    player.sendMessage("Вам очищено " + pkReduceCount + " PK.");
					    player.broadcastUserInfo();
					    return "PkServices-Success.htm";
					}
					return "PkServices-NoItems.htm";
                }
				return "PkServices-NoPks.htm";
            }
            catch (Exception e)
            {
                player.sendMessage("Произошла ошибка, повторите действие.");
                return "PkServices.htm";
            }
        }
        else if (event.startsWith("changeClanName"))
        {
        	if (player.getClan() == null)
        	{
        		return "ChangeClanName-NoClan.htm";
        	}
			try
			{
				String newClanName = event.substring(15);
				
				if (st.getQuestItemsCount(changeClanNameItemId) >= changeClanNameItemCount)
				{
					if (newClanName == null)
					{
						return "ChangeClanName.htm";
					}
					if (!player.isClanLeader())
					{
						player.sendMessage("Вы не клан лидер.");
						return "ChangeClanName.htm";
					}
					else if (player.getClan().getLevel() < clanMinLevel)
					{
						player.sendMessage("Доступно только кланам " + clanMinLevel + " уровня.");
						return "ChangeClanName.htm";
					}
					else if (!newClanName.matches("^[a-zA-Z0-9]+$"))
					{
					    player.sendMessage("Некорректное название клана.");
					    return "ChangeClanName.htm";
					}
					else if (newClanName.equals(player.getClan().getName()))
					{
					    player.sendMessage("Некорректное название клана.");
					    return "ChangeClanName.htm";
					}
					else if (ClanTable.getInstance().getClanByName(newClanName) != null)
					{
					    player.sendMessage("Название клана: " + newClanName + " уже занято.");
					    return "ChangeClanName.htm";
					}
					else
					{
					    st.takeItems(changeNameItemId, changeNameItemCount);
					    player.getClan().setName(newClanName);
					    
					    try (Connection con = L2DatabaseFactory.getInstance().getConnection())
					    {
					    	PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET clan_name=? WHERE clan_id=?");
					    	statement.setString(1, newClanName);
					    	statement.setInt(2, player.getClan().getClanId());
					    	statement.execute();
					    	statement.close();
					    }
					    catch (Exception e)
					    {
					    	_log.info("Error updating clan name for player " + player.getName() + ". Error: " + e);
					    }
					    
					    player.sendMessage("Вы изменили название клана на: " + newClanName);
					    player.getClan().broadcastClanStatus();
					    return "ChangeClanName-Success.htm";
					}
				}
				return "ChangeClanName-NoItems.htm";
			}
			catch (Exception e)
			{
			    player.sendMessage("Произошла ошибка, повторите действие.");
			    return "ChangeClanName.htm";
			}
        }
        else if (event.startsWith("setReputationPoints"))
        {
            try
            {
                String reputationPointsString = event.substring(20);
                int reputationPointsCount = Integer.parseInt(reputationPointsString);
                
                if (player.getClan() == null)
                {
                	return "ClanReputationPoints-NoClan.htm";
                }
                else if (!player.isClanLeader())
                {
                	return "ClanReputationPoints-NoLeader.htm";
                }
                else
                {
	                if (reputationPointsCount == 0)
	                {
	                    player.sendMessage("Введите значение больше 0");
	                    return "ClanReputationPoints.htm";
	                }
					if (st.getQuestItemsCount(clanReputationPointsItemId) >= clanReputationPointsItemCount)
					{
						st.takeItems(clanReputationPointsItemId, clanReputationPointsItemCount * reputationPointsCount);
					    player.getClan().addReputationScore(reputationPointsCount);
					    player.getClan().broadcastClanStatus();
					    return "ClanReputationPoints-Success.htm";
					}
					return "ClanReputationPoints-NoItems.htm";
                }
            }
            catch (Exception e)
            {
                player.sendMessage("Произошла ошибка, повторите действие.");
                return "ClanReputationPoints.htm";
            }
        }
        
        return htmlText;
	}
}